#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include "daemon_runner.h"
#include "daemon_sub_process.h"

static int is_running = 1;
static sub_process_t* sub_process_arr[2];
static void daemon_runner_stop(int sig)
{
    if (sig == SIGTERM)
    {
        is_running = 0;
    }
    
}

/**
 * @brief 启动守护进程
 * 
 * @return int 成功返回0 失败返回-1
 */
int daemon_runner_start(void)
{

    /*1.设置为守护进程*/
    daemon(0,1);
    /*2.重定向日志信息*/
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    open("gateway.log",O_CREAT|O_RDWR,0666);
    open("gateway.err",O_CREAT|O_RDWR,0666);
    /*3.注册结束信号*/
    signal(SIGTERM,daemon_runner_stop);
    /*4.初始化子进程*/
    sub_process_arr[0] = daemon_sub_process_Init("app");
    sub_process_arr[1] = daemon_sub_process_Init("ota");
    /*5.循环检查子进程状态并拉扶*/
    while (is_running)
    {
        for (int i = 0; i < 2; i++)
        {
            daemon_sub_process_check_start(sub_process_arr[i]);
        }
        sleep(3);
    }
    /*6.若守护进程中止则同时中止下面的子进程*/
    for (int i = 0; i < 2; i++)
    {
        daemon_sub_process_destroy(sub_process_arr[i]);
    }

    return 0;
}